<template>
  <el-card>
    <h2>新闻稿列表</h2>
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form" style="margin-bottom: 20px;">
      <el-form-item label="新闻稿ID">
        <el-input v-model="searchForm.announcementId" placeholder="请输入新闻稿ID" clearable />
      </el-form-item>
      <el-form-item label="关键字">
        <el-input v-model="searchForm.keywords" placeholder="请输入标题或内容关键字" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="notices" style="width: 100%">
      <el-table-column prop="id" label="新闻稿ID" width="90" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="content" label="内容" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column prop="orgId" label="组织ID" width="100" />
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button size="small" @click="editNotice(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteNotice(scope.row)">删除</el-button>
          <el-button size="small" @click="goNoticeDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑新闻稿对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑新闻稿" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="editForm.title" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="editForm.content" type="textarea" :rows="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 查看新闻稿对话框 -->
    <el-dialog v-model="viewDialogVisible" title="新闻稿详情" width="500px" :show-close="true">
      <div>
        <p><strong>标题：</strong>{{ viewForm.title }}</p>
        <p><strong>内容：</strong>{{ viewForm.content }}</p>
        <p><strong>更新时间：</strong>{{ viewForm.updateTime }}</p>
        <p><strong>组织ID：</strong>{{ viewForm.orgId }}</p>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

const orgId = localStorage.getItem('loginId')
const notices = ref([])

const searchForm = ref({
  announcementId: '',
  keywords: ''
})

// 默认加载全部新闻稿
const fetchAllNotices = async () => {
  try {
    const res = await axios.get(`http://localhost:8080/orgs/${orgId}/announcements`)
    if (res.data && res.data.code === 200) {
      notices.value = res.data.data || []
    } else {
      notices.value = []
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取新闻稿失败')
    }
  } catch (e) {
    ElMessage.error('获取新闻稿失败')
  }
}

onMounted(fetchAllNotices)

// 搜索功能
const handleSearch = async () => {
  // 优先按新闻稿ID搜索
  if (searchForm.value.announcementId) {
    try {
      const res = await axios.get(`http://localhost:8080/orgs/announcements/${searchForm.value.announcementId}`)
      if (res.data && res.data.code === 200 && res.data.data) {
        notices.value = [res.data.data]
      } else {
        notices.value = []
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '未找到该新闻稿')
      }
      return
    } catch (e) {
      ElMessage.error('搜索失败')
      return
    }
  }
  // 按关键字搜索
  if (searchForm.value.keywords) {
    try {
      const res = await axios.get(`http://localhost:8080/orgs/${orgId}/${searchForm.value.keywords}/announcements/search`)
      if (res.data && res.data.code === 200) {
        notices.value = res.data.data || []
      } else {
        notices.value = []
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '搜索失败')
      }
      return
    } catch (e) {
      ElMessage.error('搜索失败')
    }
  }
  fetchAllNotices()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.announcementId = ''
  searchForm.value.keywords = ''
  fetchAllNotices()
}

// 编辑新闻稿
const editDialogVisible = ref(false)
const editForm = ref({
  id: '',
  title: '',
  content: ''
})

const editNotice = (row) => {
  editForm.value = { ...row }
  editDialogVisible.value = true
}

const submitEdit = async () => {
  try {
    const res = await axios.put(
      `http://localhost:8080/${editForm.value.id}/${orgId}/announcements`,
      {
        "id": editForm.value.id,
        "title": editForm.value.title,
        "content": editForm.value.content,
        "orgId": Number(orgId)
      }
    )
    if (res.data && res.data.code === 200) {
      ElMessage.success('新闻稿修改成功')
      editDialogVisible.value = false
      fetchAllNotices()
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '修改失败')
    }
  } catch (e) {
    ElMessage.error('修改失败')
  }
}

// 删除新闻稿
const deleteNotice = (row) => {
  ElMessageBox.confirm('确定要删除该新闻稿吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await axios.delete(`http://localhost:8080/announcements/${row.id}/${orgId}`)
      if (res.data && res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchAllNotices()
      } else {
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '删除失败')
      }
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

// 查看新闻稿
const viewDialogVisible = ref(false)
const viewForm = ref({
  id: '',
  title: '',
  content: '',
  updateTime: '',
  orgId: ''
})

const goNoticeDetail = (row) => {
  router.push({ name: 'AnnouncementDetail', params: { id: row.id } })
}
</script>